import 'dart:convert';
import 'dart:ui';

import 'package:coin_genarate/coin_generate_manager.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_basic_widgets/toast/toast_manager.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:flutter_lifecycle_base/base_state_widget.dart';
import 'package:flutter_lifecycle_base/widget/status_bar_wrap.dart';
import 'package:route_manager/app_config.dart';
import 'package:route_manager/wx_navigator.dart';
import 'package:wallet_home/constant/sp_key_config.dart';
import 'package:wallet_home/model/coin_detail_model/coin_detail_list_model.dart';
import 'package:wallet_home/model/wallet_list_model.dart';
import 'package:wallet_home/page/theme/colors.dart';
import 'package:wallet_home/tools/aes_util.dart';
import 'package:wallet_home/tools/theme_utils.dart';
import 'package:wallet_home/widget/coins_manager.dart';
import 'package:wallet_home/widget/transfer_main_stepper_widget.dart';

import '../image_r.dart';
import '../module_config.dart';

class TransferMainPage extends BaseStatefulWidget {
  @override
  _TransferMainPageState createState() => _TransferMainPageState();
}

class _TransferMainPageState extends BaseWidgetState<TransferMainPage> {
  int groupValue = 0;

  CoinsBean _bean;

  CoinsBean _coinDetailBean;

  bool isOverlayShow = false;
  bool isFeeOverlayShow = false;

  TextEditingController _addressEditingController;
  TextEditingController _numberEditingController;

  FocusNode _addressNode;
  FocusNode _numberNode;

  GlobalKey feeKey = GlobalKey();

  Offset feeOffsetRight;

  Color buttonTransferColor = Colors.grey[400];
  bool isButtonEnable = false;
  bool isPageClick = false;

  int position = 1;

  double lowFee = 0.002;
  double midFee = 0.005;
  double highFee = 0.007;

  double kFee = 0.0;
  double kCNYFee = 0.0;

  String numberInputText = "";

  @override
  void initState() {
    super.initState();
    //isButtonEnable = true;

    _addressEditingController = TextEditingController();
    _numberEditingController = TextEditingController();

    _addressNode = FocusNode();
    _numberNode = FocusNode();

    feeOffsetRight = Offset(0, 0);

    _addressNode.addListener(() {
      if (_addressNode.hasFocus) {
        print("地址框有焦点");
        SystemChannels.textInput.invokeMethod('TextInput.show');
      } else {
        print("地址框无焦点");
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      }
    });

    _numberNode.addListener(() {
      if (_numberNode.hasFocus) {
        print("数量框有焦点");
        SystemChannels.textInput.invokeMethod('TextInput.show');
      } else {
        print("数量框无焦点");
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      RenderBox box = feeKey.currentContext.findRenderObject();
      Offset feeOffset = box.localToGlobal(Offset.zero);
      feeOffsetRight = Offset(feeOffset.dx + box.size.width, feeOffset.dy);
    });
  }

  @override
  Widget build(BuildContext context) {
    buttonTransferColor = ThemeUtils.getThemeColor(
        context: context,
        brightnessColor: Colours.app_main,
        darkColor: Colours.color_gold);
    _bean = ModalRoute.of(context).settings.arguments;
    _coinDetailBean = CoinManager().getSingleCoinDetailModel(_bean.title);
    //  _addressEditingController.text = _bean.address;
    print("address=======>${_bean.address}");
    return MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: StatusBarWrap(
          child: Scaffold(
            resizeToAvoidBottomInset: false,
              body: SafeArea(
                child: GestureDetector(
                    onTapDown: (down) {
                      print("page tap");
                      isPageClick = true;
                      if (isOverlayShow) {
                        isOverlayShow = false;
                      }

                      if (isFeeOverlayShow) {
                        isFeeOverlayShow = false;
                      }
                      setState(() {});
                    },
                    onTapUp: (up) {
                      print("page tap up");
                      isPageClick = false;
                    },
                    onTapCancel: () {
                      print("page tap cancel");
                      isPageClick = false;
                    },
                      child: Stack(
                        children: [
                          Container(
                            width: MediaQuery.of(context).size.width,
                            height: MediaQuery.of(context).size.height,
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Container(
                                  height: 170,
                                  width: double.infinity,
                                  color: ThemeUtils.getThemeColor(
                                      context: context,
                                      brightnessColor: Colours.app_main,
                                      darkColor: Colors.black87),
                                  child: Column(
                                    children: [
                                      _transferMainHeader(),
                                      _flexibleSpaceWidget(),
                                    ],
                                  ),
                                ),
                                Expanded(
                                    child: Container(
                                      width: MediaQuery.of(context).size.width,
                                      child: _transferMainContent(),
                                    ))
                              ],
                            ),
                          ),
                          _showOverlay(context),
                          _showFeeOverlay(context),
                          _transferMainBottomButton()
                        ],
                    )),
              )),
        ));
  }

  _transferMainContent() {
    return Column(
      children: [_addressArea(), _numberArea(), _transferFeeArea()],
    );
  }

  _transferMainBottomButton() {
    return Positioned(
      child: GestureDetector(
        onTapDown: (down) {
          print("TapDown ======>$isButtonEnable");
          if (isButtonEnable) {
            buttonTransferColor = Colors.grey[400];
            setState(() {});
          }
        },
        onTapUp: (up) {
          if(!isButtonEnable) return;
          Future.delayed(Duration(milliseconds: 50), () {
            print("TapUp======>$isButtonEnable");
            if (isButtonEnable) {
              buttonTransferColor = ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colours.app_main,
                  darkColor: Colours.color_gold);
              setState(() {});
            }
          });
          _clickConfirmButton();
        },
        onTapCancel: () {
          if(!isButtonEnable) return;
          buttonTransferColor = ThemeUtils.getThemeColor(
              context: context,
              brightnessColor: Colours.app_main,
              darkColor: Colours.color_gold);
          setState(() {});
        },
        child: Container(
          height: 50,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(6)),
              color: isButtonEnable ? buttonTransferColor : Colors.grey[400]),
          alignment: Alignment.center,
          child: Text(
            "${WXLang.$t("home_confirm",package: ModuleConfig.moduleName)}",
            style: TextStyle(color: Colors.white, fontSize: 18),
          ),
        ),
      ),
      left: 10,
      right: 10,
      bottom: 15,
    );
  }

  /// 地址区域
  _addressArea() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.only(top: 10, left: 15),
          child: Text(
            "${WXLang.$t("home_title_address",package: ModuleConfig.moduleName)}",
            style: TextStyle(
                color: ThemeUtils.getThemeColor(
                    context: context,
                    brightnessColor: Colors.grey[800],
                    darkColor: Colors.white),
                fontSize: 12),
          ),
        ),
        Container(
          height: 45,
          padding: EdgeInsets.only(top: 5, left: 15),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(child: _addressEditArea()),
              Container(
                margin: EdgeInsets.only(right: 20, top: 5),
                child: InkWell(
                    onTap: () {
                      isFeeOverlayShow = false;
                      WXNavigator.pushNamed(
                              routeName: "/addressBookPage",
                              arguments: "transfer")
                          .then((value) =>
                              _addressEditingController.text = value);
                      setState(() {

                      });
                    },
                    child: Image.asset(ImageR.imagesAddressBookIcon,
                        color: ThemeUtils.getThemeColor(
                            context: context,
                            brightnessColor: Colors.grey[600],
                            darkColor: Colors.white),
                        height: 40,
                        width: 40,
                        fit: BoxFit.cover,
                        package: ModuleConfig.moduleName)),
              )
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 12),
          height: 0.5,
          width: double.infinity,
          color: Colors.grey[400],
        )
      ],
    );
  }

  /// 地址区域
  _numberArea() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.only(top: 10, left: 15),
          child: Text(
            "${WXLang.$t("home_amount",package: ModuleConfig.moduleName)}",
            style: TextStyle(
                color: ThemeUtils.getThemeColor(
                    context: context,
                    brightnessColor: Colors.grey[800],
                    darkColor: Colors.white),
                fontSize: 12),
          ),
        ),
        Container(
          height: 45,
          padding: EdgeInsets.only(top: 5, left: 15),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(child: _numberEditArea()),
              Container(
                margin: EdgeInsets.only(right: 20, top: 5),
                child: InkWell(
                  child: Text(
                    "${WXLang.$t("home_send_all",package: ModuleConfig.moduleName)}",
                    style: TextStyle(color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colours.app_main,
                        darkColor: Colours.color_gold), fontSize: 14),
                  ),
                  onTap: () {
                    isOverlayShow = false;
                    isFeeOverlayShow = false;
                    kCNYFee = getCNYFee(index: position, isAll: true);
                    setState(() {});
                  },
                ),
              )
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 12),
          height: 0.5,
          width: double.infinity,
          color: Colors.grey[400],
        )
      ],
    );
  }

  ///地址输入框
  _addressEditArea() {
    return Form(
      child: TextFormField(
          // keyboardType: TextInputType.emailAddress,
          textInputAction: TextInputAction.done,
          onChanged: (value) {
            if(_addressEditingController.text.isEmpty || _numberEditingController.text.isEmpty){
                isButtonEnable = false;
            }else{
              isButtonEnable = true;
            }
            setState(() {

            });
          },
          onTap: () {
            isOverlayShow = false;
            isFeeOverlayShow = false;
            _numberNode.unfocus();
            Future.delayed(Duration(milliseconds: 250)).then((value) {
              FocusScope.of(context).requestFocus(_addressNode);
            });
          },
          focusNode: _addressNode,
          inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp("[a-z,A-Z,0-9]"))
            //LengthLimitingTextInputFormatter(19), //限制长度
          ],
          cursorHeight: 20,
          controller: _addressEditingController,
          decoration: _getDecoration("${WXLang.$t("home_input_address",package: ModuleConfig.moduleName)}")),
    );
  }

  ///数量输入框
  _numberEditArea() {
    return Form(
      child: TextFormField(
        // keyboardType: TextInputType.number,
        textInputAction: TextInputAction.done,
        onChanged: (value) {
          numberInputText = value;
//            _numberEditingController.selection(TextSelection.fromPosition(
//                TextPosition(
//                    affinity: TextAffinity.downstream,
//                    offset: numberInputText.length)));
          kCNYFee = getCNYFee(index: position, isAll: false);

          if(_addressEditingController.text.isEmpty || _numberEditingController.text.isEmpty){
            isButtonEnable = false;
          }else{
            isButtonEnable = true;
          }
          setState(() {

          });
        },
        onTap: () {
          isOverlayShow = false;
          isFeeOverlayShow = false;
          _addressNode.unfocus();
          Future.delayed(Duration(milliseconds: 250)).then((value) {
            FocusScope.of(context).requestFocus(_numberNode);
          });
        },
        focusNode: _numberNode,
        cursorHeight: 20,
        inputFormatters: [
          FilteringTextInputFormatter.allow(RegExp("[.,0-9]"))
          //LengthLimitingTextInputFormatter(19), //限制长度
        ],
        controller: _numberEditingController,
        decoration: _getDecoration("${WXLang.$t("home_input_transfer_amount",package: ModuleConfig.moduleName)}"),
      ),
    );
  }

  InputDecoration _getDecoration(String hintText) {
    return InputDecoration(
      hintText: hintText,
      hintStyle: TextStyle(color: Color(0xFF999999), fontSize: 14.0),
      // errorText不为空时，输入框有焦点时的边框
      focusedErrorBorder: UnderlineInputBorder(
          borderSide: BorderSide(
        color: Colors.transparent,
        width: 0.0,
      )),
      // 输入框可用时显示的边框，如果errorText为空的话，该属性有效
      // 输入框没有焦点时，优先使用enabledBorder ，有焦点时，优先使用focusedBorder，两者均没有指定时，使用默认的border
      enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
        color: Colors.transparent,
        width: 0.0,
      )),
      //输入框有焦点时的边框,如果errorText为空的话，该属性有效
      focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(
        color: Colors.transparent,
        width: 0.0,
      )),
      border: UnderlineInputBorder(
          borderSide: BorderSide(
        color: Colors.transparent,
        width: 0.0,
      )),
      // hintText: '请填写内容',
      // helperText: tfModel.tips,
//          helperStyle: TextStyle(
//              color: ColorExtension.hexColor(0xE92417), fontSize: 12.0),
      contentPadding: EdgeInsets.all(1.0),
      // floatingLabelBehavior: FloatingLabelBehavior.auto,
      // 正常情况下的border
    );
  }

  _transferFeeArea() {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
              padding: EdgeInsets.only(left: 15, top: 15),
              child: Text.rich(
                TextSpan(children: [
                  TextSpan(
                      text: "${WXLang.$t("home_miner_fee",package: ModuleConfig.moduleName)}(${_bean.title}:)",
                      style: TextStyle(
                          color: ThemeUtils.getThemeColor(
                              context: context,
                              brightnessColor: Colors.grey[500],
                              darkColor: Colors.white),
                          fontSize: 12)),
                  WidgetSpan(
                      child: InkWell(
                        child: Image(
                          image: AssetImage(ImageR.imagesChargeHelpIcon,
                              package: ModuleConfig.moduleName),
                          width: 30,
                          height: 30,
                          fit: BoxFit.fill,
                        ),
                        onTap: () {
                          isOverlayShow = false;
                          isFeeOverlayShow = !isFeeOverlayShow;
                          setState(() {});
                        },
                      ),
                      alignment: PlaceholderAlignment.middle),
                ]),
                key: feeKey,
              )),
          Padding(
            padding: EdgeInsets.only(left: 15, top: 5, right: 25),
            child: Row(
              children: [
                Text(
                  "${NumUtil.getNumByValueDouble(kFee, 8).toStringAsFixed(6)}",
                  style: TextStyle(
                      color: ThemeUtils.getThemeColor(
                          context: context,
                          brightnessColor: Colors.grey[800],
                          darkColor: Colors.white),
                      fontSize: 18),
                ),
                Expanded(
                    child: Container(
                  padding: EdgeInsets.only(right: 30),
                  alignment: Alignment.centerRight,
                  child: Text(
                    "≈${NumUtil.getNumByValueDouble(kCNYFee, 8).toStringAsFixed(2)} CNY",
                    style: TextStyle(
                        color: ThemeUtils.getThemeColor(
                            context: context,
                            brightnessColor: Colors.grey[800],
                            darkColor: Colors.white),
                        fontSize: 14),
                  ),
                )),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 40, top: 15),
            child: TransferStepperWidget(
              callback: (index) {
                isOverlayShow = false;
                isFeeOverlayShow = false;
                position = index;
                kCNYFee = getCNYFee(index: index, isAll: false);
                print("stepper========>$num==========>$kFee");
                setState(() {});
              },
              lineWidth: 90,
              initialPosition: 1,
              outerCircleColor: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colors.grey[200],
                  darkColor: Color(0xFFEEEEEE)),
              innerCircleColor: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colours.app_main,
                  darkColor: Colours.color_gold),
              labelTextStyle: TextStyle(
                  color: ThemeUtils.getThemeColor(
                      context: context,
                      brightnessColor: Colors.grey[800],
                      darkColor: Colors.white70),
                  fontSize: 13),
            ),
          )
        ],
      ),
    );
  }

  _transferMainHeader() {
    return Container(
        width: double.infinity,
        height: 70,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Padding(
                padding: EdgeInsets.only(left: 10, bottom: 5),
                child: InkWell(
                  child: Image.asset(ImageR.imagesActivityTitleBack,
                      width: 30,
                      height: 30,
                      color: ThemeUtils.getThemeColor(
                          context: context,
                          brightnessColor: Colors.grey[200],
                          darkColor: Colors.white),
                      fit: BoxFit.fill,
                      package: ModuleConfig.moduleName),
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                )),
            Expanded(
                child: Container(
              padding: EdgeInsets.only(bottom: 10),
              alignment: Alignment.bottomCenter,
              child: Text(
                "${_bean.title} ${WXLang.$t("home_transfer",package: ModuleConfig.moduleName)}",
                style: TextStyle(
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[200],
                        darkColor: Colors.white),
                    fontSize: 16),
              ),
            )),
            Padding(
              padding: EdgeInsets.only(right: 15, bottom: 5),
              child: InkWell(
                child: Image.asset(ImageR.imagesQrcodeIcon,
                    width: 30,
                    height: 30,
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[200],
                        darkColor: Colors.white),
                    fit: BoxFit.fill,
                    package: ModuleConfig.moduleName),
                onTap: () {
                  _addressNode.unfocus();
                  _numberNode.unfocus();
                  Future.delayed(Duration(milliseconds: 500),() {
                      WXNavigator.pushNamed(routeName: "/qrcode_scan")
                      .then((value) {
                        if (value != null && value.length != 0) {
                          _addressEditingController.text = value;
                        }});
                  });
                },
              ),
            )
          ],
        ));
  }

  _flexibleSpaceWidget() {
    return Container(
      height: 100,
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.only(top: 5, left: 15),
            child: Text(
              "${WXLang.$t("home_total_amount",package: ModuleConfig.moduleName)}(${_bean.title})",
              style: TextStyle(
                  color: ThemeUtils.getThemeColor(
                      context: context,
                      brightnessColor: Colors.grey[200],
                      darkColor: Colors.white70)),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 8, left: 15),
            child: Text(
              _numberEditingController.text.isEmpty
                  ? "0.000000"
                  : NumUtil.getNumByValueDouble(getTotalBTCCost(), 8)
                      .toStringAsFixed(6),
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
          Row(
            children: [
              Padding(
                padding: EdgeInsets.only(top: 15, left: 15),
                child: Text(
                  "≈${NumUtil.getNumByValueDouble(getTotalCNYCost(), 8).toStringAsFixed(2)} CNY",
                  style: TextStyle(
                      color: ThemeUtils.getThemeColor(
                          context: context,
                          brightnessColor: Colors.grey[200],
                          darkColor: Colors.white),
                      fontSize: 12),
                ),
              ),
              Spacer(),
              Padding(
                padding: EdgeInsets.only(top: 10, right: 30),
                child: Text.rich(TextSpan(children: [
                  TextSpan(
                      text:
                          "${WXLang.$t("home_available",package: ModuleConfig.moduleName)} ${NumUtil.getNumByValueStr(_coinDetailBean.num).toStringAsFixed(6)} (${_bean.title})",
                      style: TextStyle(
                          color: ThemeUtils.getThemeColor(
                              context: context,
                              brightnessColor: Colors.grey[200],
                              darkColor: Colors.white),
                          fontSize: 12)),
                  WidgetSpan(
                      child: InkWell(
                        child: Image(
                          image: AssetImage(ImageR.imagesFreezeHelpIcon,
                              package: ModuleConfig.moduleName),
                          width: 25,
                          height: 25,
                          fit: BoxFit.fill,
                        ),
                        onTap: () {
                          isFeeOverlayShow = false;
                          print("icon_click  ===$isPageClick==>$isOverlayShow");
                          //  if (isPageClick && !isOverlayShow) return;
                          isOverlayShow = !isOverlayShow;
                          setState(() {});
                        },
                      ),
                      alignment: PlaceholderAlignment.middle),
                ])),
              )
            ],
          )
        ],
      ),
    );
  }

  _showOverlay(BuildContext context) {
    return Positioned(
      child: Offstage(
        offstage: !isOverlayShow,
        child: Container(
          decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.all(Radius.circular(10))),
          width: MediaQuery.of(context).size.width * 3 / 4,
          height: 120,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Padding(
                    padding: EdgeInsets.only(left: 15, top: 15),
                    child: Text(
                      "${WXLang.$t("home_frozen_quantity",package: ModuleConfig.moduleName)}：",
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                  ),
                  Spacer(),
                  Padding(
                    padding: EdgeInsets.only(right: 15, top: 16),
                    child: Text(
                      "0.00000000 ${_bean.title}",
                      style: TextStyle(color: Color(0xFFCCA881), fontSize: 15),
                    ),
                  ),
                ],
              ),
              Container(
                height: 1,
                color: Colors.grey[600],
                margin: EdgeInsets.only(right: 15, left: 15, top: 15),
              ),
              Padding(
                padding: EdgeInsets.only(left: 15, top: 20, right: 20),
                child: Text(
                  "${WXLang.$t("home_frozen_info_text",package: ModuleConfig.moduleName)}",
                  style: TextStyle(
                      color: ThemeUtils.getThemeColor(
                          context: context,
                          brightnessColor: Colors.grey[500],
                          darkColor: Colors.white),
                      fontSize: 12),
                ),
              ),
            ],
          ),
        ),
      ),
      right: 10,
      top: 170,
    );
  }

  _showFeeOverlay(BuildContext context) {
    return Positioned(
      child: Offstage(
        offstage: !isFeeOverlayShow,
        child: Container(
          decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.all(Radius.circular(10))),
          width: MediaQuery.of(context).size.width / 2 + 35,
          padding: EdgeInsets.all(10),
          child: Text(
            "${WXLang.$t("home_miner_fee_info",package: ModuleConfig.moduleName)}",
            style: TextStyle(color: ThemeUtils.getThemeColor(
                context: context,
                brightnessColor: Colors.grey[500],
                darkColor: Colors.white), fontSize: 14),
          ),
        ),
      ),
      right: 30,
      top: feeOffsetRight.dy,
    );
  }

  double getCNYFee({int index, bool isAll}) {
    double num = double.parse(_numberEditingController.text.isEmpty
        ? "0.0"
        : _numberEditingController.text.toString());
    double price = double.parse(_bean.cnyBalance);
    print("getCNYFee========>$index");

    double totalNum = double.parse(_bean.num);
    if (isAll) {
      num = totalNum;
    }

    if (index == 0) {
      kFee = num * lowFee;
    } else if (index == 1) {
      kFee = num * midFee;
    } else {
      kFee = num * highFee;
    }

    if (num + kFee > totalNum) {
      if (num > totalNum) {
        ToastManager.show("${WXLang.$t("home_input_exceed",package: ModuleConfig.moduleName)}");
      } else {
        _numberEditingController.text = totalNum.toString();
      }
    }
    return kFee * price;
  }

  /// 获取BTC总共的花费
  double getTotalBTCCost() {
    String numberText = _numberEditingController.text;
    if (numberText.isEmpty) {
      return 0.00000000;
    }
    double num = double.parse(numberText);
    double totalNum = double.parse(_bean.num);
    double totalCost = num + kFee;
    if (totalCost > totalNum) {
      return totalNum;
    }
    return totalCost;
  }

  /// 获取CNY总共的花费
  double getTotalCNYCost() {
    String balance = _bean.cnyBalance;
    if (balance.isEmpty) return 0.00000000;
    return getTotalBTCCost() * double.parse(balance);
  }

  /// 确定按钮点击
  _clickConfirmButton() async {
    final manager = CoinGenerateManager();
    String mnemonic = AESUtil.decryptString(SpUtil.getString("mnemonic_list"));
    TransactionResModel model = await manager.transactionBTC(
        mnemonic: mnemonic,
        fromAddress: _bean.address,
        toAddress: _addressEditingController.text,
        amount: getTotalBTCCost().toString(),
        fee: kFee.toString(),
        isTransfer: true);

    CoinDetailModel detailModel = CoinDetailModel();
    detailModel
      ..img = _bean.img
      ..name = _bean.title
      ..time = model.time ?? DateTime.now()
      ..upDown = getTotalBTCCost().toString()
      ..cnyMoney = getTotalCNYCost().toString()
      ..address = _addressEditingController.text.toString()
      ..transferType = "0";

    List<CoinDetailModel> modelList;
    String transferRecord = SpUtil.getString(transfer_record_key);
    if (transferRecord.isNotEmpty) {
      List list = json.decode(transferRecord);
      modelList = CoinDetailModel.fromList(list);
      modelList.add(detailModel);
    } else {
      modelList = List();
      modelList.add(detailModel);
    }
    SpUtil.putString(transfer_record_key, json.encode(modelList).toString());
    ToastManager.show("${WXLang.$t("home_transfer_success",package: ModuleConfig.moduleName)}", duration: 1000);
    CoinManager().updateCoinDetail(_bean.title, getTotalBTCCost().toString(),
        getTotalCNYCost().toString(), "0");
    WXNavigator.pop();
  }

  @override
  void dispose() {
    _addressEditingController?.dispose();
    _numberEditingController?.dispose();
    super.dispose();
  }
}
